﻿using System.Collections.Generic;
using System.Linq;
using Entropy.Ext.Ast;

namespace Entropy.Ext
{
	internal class ExtAccent : IAccent
	{
		private readonly Variable extVariable = new Variable { Name = "Ext"};

        Node IAccent.Constructor(Json json, bool treatAsJson, bool insideEventHandler)
		{
			if (treatAsJson)
			{
				if (!string.IsNullOrEmpty(json.ClassInfo.Alias))
				{

					var props = new List<SubArgument>(json.Props)
					{
						new SubArgument
						{
							Name = "xtype",
							Value = new Const(json.ClassInfo.Alias)
						}
					};
					json.Props = props.ToArray();
				}
				return json;
			}

            var ctor = new Call
            {
                Object = new Reference {Variable = extVariable}, FunctionName = "create", Arguments = new Node[]
                    {
                        new Const(json.ClassInfo.FullClassName), json
                    }
            };

            if (insideEventHandler)
            {
                // contentPanel.add(Ext.CreateNewTab
                return ctor;
            }

            return new VariableDeclareOrRefer
            {
                VarNameBasis = json.ClassInfo.Alias ?? json.ClassInfo.FullClassName.Split(new[] {'.'}).Last(),
                Ctor = ctor
            };
		}

		public Node ResolveEvent(Binary assign)
		{
			var propertyGet = ((PropertyGet) assign.Left);
			return new Call
			{
				Object = propertyGet.Object,
				FunctionName = "on",
				Arguments = new[]
				{
					new Const(propertyGet.PropName),
 					assign.Right 
				}
			};
		}
	}
}